import java.io.*;
import java.util.Scanner;

// 假设的学生类示例
class Stu implements Serializable {
    private String name;
    private int age;

    public Stu(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class FileOperationDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 创建文件夹
        File txtFolder = new File("D:/myDocument/txt");
        File serFolder = new File("D:/myDocument/ser");
        if (!txtFolder.exists()) {
            txtFolder.mkdirs();
        }
        if (!serFolder.exists()) {
            serFolder.mkdirs();
        }

        // 在txt文件夹下创建文件
        File sourceFile = new File(txtFolder, "SourceData.txt");
        File copyFile = new File(txtFolder, "CopyData.txt");
        sourceFile.createNewFile();
        copyFile.createNewFile();

        // 从键盘输入文本保存到SourceData.txt
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一行文本:");
        String inputText = scanner.nextLine();
        BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFile));
        writer.write(inputText);
        writer.close();

        // 使用缓冲区流拷贝文件内容
        BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
        BufferedWriter writerCopy = new BufferedWriter(new FileWriter(copyFile));
        String line;
        while ((line = reader.readLine())!= null) {
            writerCopy.write(line);
            writerCopy.newLine();
        }
        reader.close();
        writerCopy.close();

        // 在ser文件夹下创建文件并进行对象序列化和反序列化
        File stuDataFile = new File(serFolder, "stuData.ser");
        File copyStuDataFile = new File(serFolder, "CopyData.ser");
        stuDataFile.createNewFile();
        copyStuDataFile.createNewFile();

        Stu stu = new Stu("张三", 20);
        // 序列化对象到文件
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(stuDataFile));
        objectOutputStream.writeObject(stu);
        objectOutputStream.close();

        // 反序列化从文件中读取对象
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(stuDataFile));
        Stu deserializedStu = (Stu) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println("反序列化后的学生姓名: " + deserializedStu.getName() + ", 年龄: " + deserializedStu.getAge());
    }
}